﻿using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using CGT.GOP.Models.Account;
using OF.Utility;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using CGT.GOP.Common;
using CGT.Infrastructure.Entity;
using CGT.Infrastructure.Service;
using System.Collections.Generic;
using Dapper.Extensions;
using System.Web.ModelBinding;

namespace CGT.GOP.Controllers
{
    public class AccountController : BaseController
    {

        GovLogLoginService llService = new GovLogLoginService();//登陆日志   
        GovLogOperateService loService = new GovLogOperateService();  //操作日志    
        GovLogSafeService lsService = new GovLogSafeService();  //安全日志

        GovUserService uService = new GovUserService(); //用户     
        GovSystemSettingService ssService = new GovSystemSettingService();   //系统设置

        GovBlackListIPService blService = new GovBlackListIPService();  //黑名单IP
        GovBlackListUserService luService = new GovBlackListUserService();  //黑名单用户

        GovLoginErrorRecordIPService leripService = new GovLoginErrorRecordIPService();  //IP登陆失败记录
        GovLoginErrorRecordUserService leruService = new GovLoginErrorRecordUserService();  //用户登陆失败记录


        //
        // GET: /Account/Login
        [AllowAnonymous]
        [HttpGet]
        public ActionResult Login()
        {
            string msg = GetParam("msg");
            ViewBag.Msg = msg;
            return View();
        }

        #region 登陆

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            ResultData<string> rt = new ResultData<string>();

            //登陆日志
            GovLogLogin logLogin = new GovLogLogin() { Incident = "登录", IncidentType = 1, Description = "", UserId = 0, Result = "", Source = IPHelper.IPAddress, CreatedDate = DateTime.Now };
            //系统设置
            List<GovSystemSetting> lgnSettings = ssService.QueryAll();

            //用户参数非空验证
            if (string.IsNullOrWhiteSpace(model.UserName) || string.IsNullOrWhiteSpace(model.Password))
            {
                //记录IP登陆错误
                string msg = setLoginErrorIPRecord(logLogin.Source, lgnSettings);
                rt.status = -1;
                rt.message = msg;

                logLogin.Description = rt.message + "登录失败，找不到此用户";
                logLogin.Result = "失败";
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //查询用户
            GovUser usr = uService.GetByUserName(model.UserName);
            if (usr != null)
            {
                logLogin.UserId = usr.UserID;
            }

            //验证码验证
            rt = validateCode(model);
            if (rt.status < 0)
            {
                logLogin.Description = rt.message;
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //最大会话数验证
            rt = validateSessionMax(lgnSettings);
            if (rt.status < 0)
            {
                logLogin.Description = rt.message;
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //黑名单ip验证
            rt = validateBlackIP(logLogin);
            if (rt.status < 0)
            {
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }
            if (usr == null)
            {
                rt.message = setLoginErrorIPRecord(logLogin.Source,lgnSettings);
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //黑名单用户验证
            rt = validateBlackUser(usr, logLogin);
            if (rt.status < 0)
            {
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //其他验证
            rt = validateOthers(usr, logLogin, lgnSettings);
            if (rt.status < 0)
            {
                setLoginErrorUserRecord(usr, lgnSettings);
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //密码验证
            rt = validatePwd(model, usr, logLogin);
            if (rt.status < 0)
            {
                rt.message = setLoginErrorUserRecord(usr, lgnSettings);
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //高频登陆验证
            rt = validateMaxCountInHour(usr, logLogin, lgnSettings);
            if (rt.status < 0)
            {
                setLoginErrorUserRecord(usr, lgnSettings);
                llService.Insert(logLogin);
                return ReturnResult(rt);
            }

            //登陆成功
            logLogin.Result = "登陆成功";
            logLogin.Description = usr.UserName + "登录成功";
            resetLoginErrorRecord(usr.UserID, logLogin.Source);
            llService.Insert(logLogin);
            SSOHelper.LoginRegister(usr.UserID.ToString());

            //更新用户登陆时间
            usr.LastLoginIP = logLogin.Source;
            usr.LastLoginTime = usr.CurrentLoginTime;  //上一次登陆时间
            usr.CurrentLoginTime = DateTime.Now;       //最后一次登陆时间    
            uService.Update(usr);

            FormsPrincipal.SignIn(new UserInfo()
            {
                RoleID = usr.RoleId,
                UserId = usr.UserID,
                UserMobile = usr.UserNumber,
                UserName = usr.UserName
            }, 1);
            return ReturnResult(rt);
        }

        /// <summary>
        /// 验证码判断
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private ResultData<string> validateCode(LoginModel model)
        {
            ResultData<string> rt = new ResultData<string>();
            if (string.IsNullOrWhiteSpace(model.ValidateCode))
            {
                rt.message = "验证码已失效，请重新输入验证码";
                rt.status = -1;
            }
            else if (Session["ValidateCode"] == null)
            {
                rt.message = "验证码已失效，请刷新验证码";
                rt.status = -1;
            }
            else if (Session["ValidateCode"].ToString().ToUpper() != model.ValidateCode.ToUpper())
            {
                rt.message = "验证码不正确,请重新输入";
                rt.status = -1;
            }
            return rt;
        }

        /// <summary>
        /// 用户会话限制判断
        /// </summary>
        /// <returns></returns>
        private ResultData<string> validateSessionMax(List<GovSystemSetting> lgnSettings)
        {
            ResultData<string> rt = new ResultData<string>();
            //在线用户最大限制
            int userSessionMax = 1000;
            if (lgnSettings.Count > 0)
            {
                if (lgnSettings[0].UserSessionMax > 0)
                {
                    userSessionMax = lgnSettings[0].UserSessionMax;
                }
            }

            if (EConvert.ToInt(HttpContext.Application["UserCount"]) >= userSessionMax)
            {
                rt.status = -1;
                rt.message = "当前用户会话数超过最大限制，禁止登录";
            }
            return rt;
        }

        /// <summary>
        /// 黑名单ip验证
        /// </summary>
        /// <returns></returns>
        private ResultData<string> validateBlackIP(GovLogLogin logLogin)
        {
            ResultData<string> rt = new ResultData<string>();
            var blackIp = blService.GetByIP(logLogin.Source);
            if (blackIp != null)
            {
                rt.status = -1;
                rt.message = "该IP已经被锁定！请联系管理员";

                logLogin.Result = "失败";
                logLogin.Description = "IP被锁定，IP为" + logLogin.Source;

                //插入操作日志
                loService.Insert(new GovLogOperate()
                {
                    CreatedDate = DateTime.Now,
                    Incident = "IP地址被锁定",
                    Description = "尝试登录失败次数过多，IP地址被锁定",
                    ModuleId = 0,
                    UserId = logLogin.UserId,
                    Source = logLogin.Source,
                    IncidentType = 4
                });
            }

            return rt;
        }

        /// <summary>
        /// 黑名单用户验证
        /// </summary>
        /// <param name="usr"></param>
        /// <param name="logLogin"></param>
        /// <returns></returns>
        private ResultData<string> validateBlackUser(GovUser usr, GovLogLogin logLogin)
        {
            ResultData<string> rt = new ResultData<string>();
            GovBlackListUser blackUser = luService.GetByUser(usr.UserID);
            if (blackUser != null)
            {
                rt.status = -1;
                rt.message = "该用户已经被锁定！请联系管理员";

                logLogin.Result = "失败";
                logLogin.Description = "用户锁定，IP为" + logLogin.Source;

                //插入操作日志
                loService.Insert(new GovLogOperate()
                {
                    CreatedDate = DateTime.Now,
                    Incident = "用户锁定",
                    Description = "尝试登录失败次数过多，用户被锁定",
                    ModuleId = 0,
                    UserId = logLogin.UserId,
                    Source = logLogin.Source,
                    IncidentType = 4
                });

                //插入安全日志   
                lsService.Insert(new GovLogSafe()
                {
                    CreatedDate = DateTime.Now,
                    Description = "登录失败次数超过最大值，被加入黑名单",
                    Incident = "用户锁定",
                    IncidentType = 4,
                    IsConventional = 0,
                    IsCoreFunction = 0,
                    ModuleId = 0,
                    Source = logLogin.Source,
                    UserId = usr.UserID
                });
            }

            return rt;
        }

        /// <summary>
        /// 其他用户验证
        /// </summary>
        /// <param name="usr"></param>
        /// <param name="logLogin"></param>
        /// <param name="lgnSettings"></param>
        /// <returns></returns>
        private ResultData<string> validateOthers(GovUser usr, GovLogLogin logLogin, List<GovSystemSetting> lgnSettings)
        {
            ResultData<string> rt = new ResultData<string>();
            //允许登录ip检测
            if (usr.AllowIP != "*")
            {
                var ips = usr.AllowIP.Split(',');
                if (!ips.Contains(logLogin.Source))
                {
                    rt.status = -1;
                    rt.message = "登录失败，该设备IP不在允许IP范围内，请联系管理员添加IP";
                    logLogin.UserId = usr.UserID;
                    logLogin.Result = "失败";
                    logLogin.Description = "设备IP{" + logLogin.Source + "}不在允许IP范围内";
                }
                return rt;
            }

            //允许登录时间段检测
            var currentHour = DateTime.Now.Hour;
            if (currentHour < usr.LoginStartTime || currentHour > usr.LoginEndTime)
            {
                rt.status = -1;
                rt.message = "登录失败，不在登录时间段内，可登录时间为" + usr.LoginStartTime + "-" + usr.LoginEndTime + "时";
                logLogin.UserId = usr.UserID;
                logLogin.Result = "失败";
                logLogin.Description = "登录不在允许时间段内，登录时间为" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                //插入安全日志
                lsService.Insert(new GovLogSafe()
                {
                    CreatedDate = DateTime.Now,
                    Description = "登录失败，不在登录时间段内",
                    Incident = "登录失败",
                    IncidentType = 4,
                    IsConventional = 0,
                    IsCoreFunction = 0,
                    ModuleId = 0,
                    Source = logLogin.Source,
                    UserId = usr.UserID
                });
                return rt;
            }
            //用户超期或者密码超期
            if (DateTime.Now > usr.UserExpireDate || DateTime.Now > usr.PasswordExpireDate)
            {
                //这种情况下需要设置用户状态不可用
                usr.State = 2;
                usr.UpdateTime = DateTime.Now;
                uService.Update(usr);

                rt.status = -1;
                rt.message = "登录失败，用户或密码已超过使用期限，请联系管理员续期";
                logLogin.UserId = usr.UserID;
                logLogin.Result = "失败";
                logLogin.Description = "用户或密码已超过使用期限,登录时间为" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                return rt;
            }

            if (lgnSettings.Count > 0)
            {
                //用户长期未登录，超过最大限制时间
                var maxUnuseDays = lgnSettings[0].UserUnuseTimeMax;//未登录最长时间限制天数
                int unuseDays = 0;
                //如果创建之后就没登录过
                if (usr.LastLoginTime.IsNullDateTime() == true)
                    unuseDays = (DateTime.Now - usr.CreateDateTime).Days + 1;//未登录天数
                else
                    unuseDays = (DateTime.Now - usr.LastLoginTime).Days + 1;//未登录天数
                if (maxUnuseDays <= unuseDays)
                {
                    //插入安全日志
                    lsService.Insert(new GovLogSafe()
                    {
                        CreatedDate = DateTime.Now,
                        Description = string.Format("用户已经{0}天未登录，超过最大限制时间{1}天,", unuseDays.ToString(), maxUnuseDays.ToString()),
                        Incident = "登录成功，超期未登录触发安全策略",
                        IncidentType = 4,
                        IsConventional = 0,
                        IsCoreFunction = 0,
                        ModuleId = 0,
                        Source = logLogin.Source,
                        UserId = usr.UserID
                    });

                    //修改用户状态为锁定状态
                    usr.State = 2;
                    usr.UpdateTime = DateTime.Now;
                    uService.Update(usr);

                    rt.status = -1;
                    rt.message = "超期未登录触发安全策略";
                }
            }
            return rt;
        }

        /// <summary>
        /// 密码验证
        /// </summary>
        /// <param name="model"></param>
        /// <param name="usr"></param>
        /// <param name="logLogin"></param>
        /// <returns></returns>
        private ResultData<string> validatePwd(LoginModel model, GovUser usr, GovLogLogin logLogin)
        {
            ResultData<string> rt = new ResultData<string>();
            if (model.Password != usr.PassWord)
            {
                logLogin.UserId = usr.UserID;
                logLogin.Result = "失败";
                logLogin.Description = usr.UserName + "登录失败，密码不正确,用户输入的密码为:" + model.Password;

                rt.status = -1;
                rt.message = "登录失败，帐号或密码不正确！当前用户可失败次数还有{0}次";
            }
            return rt;
        }

        /// <summary>
        /// 高频登陆验证
        /// </summary>
        /// <param name="usr"></param>
        /// <param name="logLogin"></param>
        /// <param name="lgnSettings"></param>
        /// <returns></returns>
        private ResultData<string> validateMaxCountInHour(GovUser usr, GovLogLogin logLogin, List<GovSystemSetting> lgnSettings)
        {
            ResultData<string> rt = new ResultData<string>();
            if (lgnSettings.Count > 0)
            {
                var maxCountInHour = lgnSettings[0].UserLoginTimesMax;
                var loginLogInHours = llService.GetList(usr.UserID, DateTime.Now.AddHours(-1), DateTime.Now).Count;
                if (loginLogInHours >= maxCountInHour)
                {

                    logLogin.UserId = usr.UserID;
                    logLogin.Result = "失败";
                    logLogin.Description = usr.UserName + "登录失败，触发高频限制";

                    //插入安全日志
                    lsService.Insert(new GovLogSafe()
                    {
                        CreatedDate = DateTime.Now,
                        Description = string.Format("高频访问策略为{0}次/小时，当前用户登录频率为{1}次/小时", maxCountInHour.ToString(), (loginLogInHours + 1).ToString()),
                        Incident = "登录失败",
                        IncidentType = 4,
                        IsConventional = 0,
                        IsCoreFunction = 0,
                        ModuleId = 0,
                        Source = logLogin.Source,
                        UserId = usr.UserID
                    });

                    rt.message = "登录失败，此用户已触发高频登录限制，请一小时后重试";
                    rt.status = -1;

                    setLoginErrorUserRecord(usr, lgnSettings);
                }
            }
            return rt;
        }

        /// <summary>
        /// 登陆成功后重置IP、UserId的失败次数为0
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userIP"></param>
        private void resetLoginErrorRecord(int userId, string userIP)
        {
            //重置失败IP次数
            var error = leripService.GetByIp(userIP);
            if (error != null)
            {
                error.ErrorCount = 0;
                error.UpdatedTime = DateTime.Now;
                leripService.Update(error);
            }

            //重置失败用户次数
            var errorUser = leruService.GetByUser(userId);
            if (errorUser != null)
            {
                errorUser.ErrorCount = 0;
                errorUser.UpdatedTime = DateTime.Now;
                leruService.Update(errorUser);
            }
        }

        /// <summary>
        /// 登陆失败时，记录UserId的失败次数，达到阀值则锁定用户
        /// </summary>
        /// <param name="usr"></param>
        /// <param name="lgnSettings"></param>
        private string setLoginErrorUserRecord(GovUser usr, List<GovSystemSetting> lgnSettings)
        {
            var errorUser = leruService.GetByUser(usr.UserID);
            //第一次
            if (errorUser == null)
            {
                errorUser = new GovLoginErrorRecordUser()
                {
                    UserID = usr.UserID,
                    ErrorCount = 1,
                    UpdatedTime = DateTime.Now
                };
                leruService.Insert(errorUser);
            }
            else //已经有记录
            {
                errorUser.ErrorCount += 1;
                errorUser.UpdatedTime = DateTime.Now;
                leruService.Update(errorUser);

                //user失败达到阀值，写入用户黑名单
                if (lgnSettings.Count > 0 && errorUser.ErrorCount >= lgnSettings[0].UserLockThreshold)
                {
                    var blackUser = luService.GetByUser(usr.UserID);
                    //黑名单已经存在则不重复拉黑
                    if (blackUser == null)
                    {
                        var info = new GovBlackListUser()
                        {
                            UserID = usr.UserID,
                            CreatedTime = DateTime.Now
                        };
                        luService.Insert(info);
                    }

                    //修改用户状态为锁定状态
                    usr.State = 2;
                    usr.UpdateTime = DateTime.Now;
                    uService.Update(usr);
                }
            }

            int userAllowCount = 0;
            if (lgnSettings.Count > 0)
            {
                userAllowCount = lgnSettings[0].UserLockThreshold - errorUser.ErrorCount;
            }
            if (userAllowCount > 0)
            {
                return string.Format("登录失败，帐号或密码不正确！当前用户可失败次数还有{0}次", userAllowCount);
            }
            return "用户已被锁定,请联系管理员";
        }

        /// <summary>
        /// 登陆失败时，记录IP的失败次数，达到阀值则锁定用户
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="lgnSettings"></param>
        /// <returns></returns>
        private string setLoginErrorIPRecord(string ip, List<GovSystemSetting> lgnSettings)
        {
            var errorIP = leripService.GetByIp(ip);
            ////第一次失败记录IP
            if (errorIP == null)
            {
                errorIP = new GovLoginErrorRecordIP()
                {
                    IP = ip,
                    ErrorCount = 1,
                    UpdatedTime = DateTime.Now
                };
                leripService.Insert(errorIP);
            }
            else
            {
                errorIP.ErrorCount += 1;
                errorIP.UpdatedTime = DateTime.Now;
                leripService.Update(errorIP);
                //ip失败达到阀值，写入ip黑名单
                if (lgnSettings.Count > 0 && errorIP.ErrorCount >= lgnSettings[0].IPLockThreshold)
                {
                    //已经在ip黑名单内则不写入
                    var ipBlack = blService.GetByIP(ip);
                    if (ipBlack == null)
                    {
                        blService.Insert(new GovBlackListIP()
                        {
                            IP = ip,
                            CreatedTime = DateTime.Now
                        });
                    }
                }
            }

            int IPAllowCount = 0;
            if (lgnSettings.Count > 0)
            {
                IPAllowCount = lgnSettings[0].IPLockThreshold - errorIP.ErrorCount;
            }
            if (IPAllowCount > 0)
            {
                return string.Format("登录失败，帐号或密码不正确！当前IP可失败次数还有{0}次", IPAllowCount);
            }
            return "当前IP已被锁定,请联系管理员";
        }

        #endregion

        #region 验证码

        [AllowAnonymous]
        [HttpGet]
        public ActionResult GetValidateCode()
        {
            string randomCode = RandomHelper.GetRandWord(4);      
            byte[] bytes = CreateValidateGraphic(randomCode);
            Session["ValidateCode"] = randomCode;
            return File(bytes, @"image/jpeg");
        }

        private byte[] CreateAuthCode(string str)
        {
            Font fn = new Font("宋体", 12);
            Brush forecolor = Brushes.Black;
            Brush bgcolor = Brushes.White;
            PointF pf = new PointF(5, 5);
            Bitmap bitmap = new Bitmap(100, 25);
            Rectangle rec = new Rectangle(0, 0, 100, 25);
            Graphics gh = Graphics.FromImage(bitmap);
            gh.FillRectangle(bgcolor, rec);
            gh.DrawString(str, fn, forecolor, pf);

            //画图片的边框线
            gh.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);

            //保存图片数据
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            //输出图片流
            return stream.ToArray();
        }

        public byte[] CreateValidateGraphic(string validateCode)
        {
            using (Bitmap map = new Bitmap(80, 30))
            {
                using (Graphics g = Graphics.FromImage(map))
                {
                    g.Clear(Color.White);//填充颜色
                    Random r = new Random();
                    //验证码
                    string[] font = { "黑体", "隶书", "楷体", "宋体", "微软雅黑" };
                    Brush[] B = { Brushes.Black, Brushes.Blue, Brushes.Red, Brushes.Green, Brushes.OrangeRed };
                    for (int i = 0; i < validateCode.Length; i++)
                    {
                        g.DrawString(validateCode[i].ToString(), new Font(font[i], 20), B[i], new Point(i * 15, 0));
                    }
                    //划线                    
                    for (int i = 0; i < 3; i++)
                    {
                        Point p1 = new Point(r.Next(0, map.Width), r.Next(map.Height));
                        Point p2 = new Point(r.Next(0, map.Width), r.Next(map.Height));
                        g.DrawLine(new Pen(Brushes.Red), p1, p2);
                    }
                    ////画点
                    //for (int i = 0; i < 200; i++)
                    //{
                    //    map.SetPixel(r.Next(0, map.Width), r.Next(map.Height), Color.Red);
                    //}
                }

                //保存图片数据
                MemoryStream stream = new MemoryStream();
                map.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
        }

        ///// <summary>
        ///// 创建验证码的图片
        ///// </summary>
        ///// <param name="containsPage">要输出到的page对象</param>
        ///// <param name="validateNum">验证码</param>
        //public byte[] CreateValidateGraphic(string validateCode)
        //{
        //    Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
        //    Graphics g = Graphics.FromImage(image);
        //    try
        //    {
        //        //生成随机生成器
        //        Random random = new Random();
        //        //清空图片背景色
        //        g.Clear(Color.White);
        //        //画图片的干扰线
        //        for (int i = 0; i < 25; i++)
        //        {
        //            int x1 = random.Next(image.Width);
        //            int x2 = random.Next(image.Width);
        //            int y1 = random.Next(image.Height);
        //            int y2 = random.Next(image.Height);
        //            g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        //        }
        //        Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
        //        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
        //         Color.Blue, Color.DarkRed, 1.2f, true);
        //        g.DrawString(validateCode, font, brush, 3, 2);
        //        //画图片的前景干扰点
        //        for (int i = 0; i < 100; i++)
        //        {
        //            int x = random.Next(image.Width);
        //            int y = random.Next(image.Height);
        //            image.SetPixel(x, y, Color.FromArgb(random.Next()));
        //        }
        //        //画图片的边框线
        //        g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
        //        //保存图片数据
        //        MemoryStream stream = new MemoryStream();
        //        image.Save(stream, ImageFormat.Jpeg);
        //        //输出图片流
        //        return stream.ToArray();
        //    }
        //    finally
        //    {
        //        g.Dispose();
        //        image.Dispose();
        //    }
        //}

        #endregion

        #region 登陆成功
        public ActionResult Index()
        {
            GovUser user = uService.Single(CurrentUser.UserId);
            return View(user);
        }

        /// <summary>
        /// 据上次登录间隔时间段内所有失败的情况
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ContentResult UserFailLog()
        {
            ResultData<List<GovLogLogin>> rt = new ResultData<List<GovLogLogin>>();
            GovUser user = uService.Single(CurrentUser.UserId);
            if (user!=null)
            {
                int pageIndex = GetPageIndex();
                int pageSize = GetPageSize();
                Page<GovLogLogin> page = llService.GetLastTimeLoginFailPages(CurrentUser.UserId, user.LastLoginTime, user.CurrentLoginTime, pageIndex, pageSize);
                return ReturnResult(new ResultPageData<List<GovLogLogin>>
                {
                    data = page.rows,
                    total = page.total
                });
            }
            return ReturnResult(rt);
        }
        #endregion

        #region 注销
        public ContentResult LoginOut()
        {
            ResultData<string> rt = new ResultData<string>();
            try
            {
                FormsPrincipal.SignOut();
                GovLogLogin logLogin = new GovLogLogin{ Incident = "登出", IncidentType = 2, Description = CurrentUser.UserName+ "退出登陆", UserId = CurrentUser.UserId, Result = "退出成功", Source = IPHelper.IPAddress, CreatedDate = DateTime.Now };
                llService.Insert(logLogin);
            }
            catch (Exception ex)
            {
                rt.data = ex.Message;
                rt.status = -1;
                rt.message = "注销失败";
            }
            return ReturnResult(rt);
        }
        #endregion
    }
}